const api = require("../../../ws_micro_shop/utils/api.js");
const app = getApp();

Page({
  data: {
    isShow: false,
    status: 1,
    type: 0,
    page: 1,
    limit: 15,
    keywords: "",
    catlist: [],
    list: [],
    currVal: "",
    is_more: true,
    isEmpty: true,
    downNum: 0,
    upNum: 0,
    goodsID: 0,
    showModel1: false,
    showModel2: false,
    showModel3: false,
    originalPrice: 0,
    salesPrice: 0,
    leaveCount: 0,
    unit: "",
    catid: "",
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-15.png',
      text: "暂无商品"
    },
    isBrand: false,
    isData1: false,
    isData2: false,
    imgUrl: app.imgUrl,
  },
  onLoad(options) {
    let that = this;
    let type = Number(options.type);
    let { page, keywords, limit, status } = that.data;
    this.setData({
      orgPrice: app.ws_micro_shop_globalData.orgPrice,
      isData1: false,
      isData2: false,
      type: type
    });
  },

  onShow(){
    let that = this;
    let { status, keywords, page, limit,type} = this.data;
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
        type,
        list:[]
      });
    });
    let title = type === 0 ? "商品管理" : type === 1 ? "库存盘点" : "产品查询";
    wx.setNavigationBarTitle({
      title: title
    });
    this.setData({
      type: type || 0,
      isBrand:
        app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.isBrand
    });
    this.onLoadGoodsCat().then(res => {
      res && res[0] && this.onGetGoodsList(res[0].id, status, keywords, page, limit);
    });
  },
  onNavigate(e) {
    let { status, keywords = '', page = 1, limit = 15 } = e.currentTarget.dataset;
    this.setData(
      {
        status,
        page: 1,
        list: [],
        isData2: false,
      },
      () => {
        this.onLoadGoodsCat().then(res => {
          res && res[0] && this.onGetGoodsList(res[0].id, status, keywords, page, limit);
        });
      }
    );
  },
  onLoadMoreData() {
    let catid = this.data.catid;
    let status = this.data.status;
    let page = this.data.page;
    let keywords = this.data.keywords;
    let limit = this.data.limit;
    if (this.data.is_more) {
      page += 1;
      this.onGetGoodsList(catid, status, keywords, page, limit);
      this.setData({
        page
      });
    }
  },
  onLoadGoodsCat() {
    let that = this;
    return new Promise((resolve, reject) => {
      app.ws_micro_shoprequest({
        url: api.default.cat_list,
        success: function(res) {
          if (res.data && res.code === 0) {
            that.setData({
              catlist: res.data.list || [],
              catid: res.data.list && res.data.list[0] ? res.data.list[0].id : '',
              isData1: true
            });
            resolve(res.data.list);
          }
        },
        fail: function(res) {
          reject(res);
        }
      });
    });
  },
  chooseCat(e) {
    let status = this.data.status;
    let limit = this.data.limit;
    this.setData({
      catid: e.currentTarget.dataset.cid,
      list: [],
      page: 1,
      currVal: "",
      is_more: true,
      isData2: false,
      isEmpty:true
    },() => {
      this.onGetGoodsList(e.currentTarget.dataset.cid, status, "", 1, limit);
    });
  },
  onGetGoodsList(cat_id, status, keywords, page, limit) {
    let that = this;
    let googslist = that.data.list;
    let _type = Number(that.data.status);
    let type = Number(that.data.type);
    wx.showToast({
      title: "加载中...",
      icon: "loading"
    });
    app.ws_micro_shoprequest({
      url: api.adminer.new_goods,
      data: {
        cat_id,
        status,
        keywords,
        page,
        limit,
        stock_alarm: type != 1 ? 0 : type
      },
      success: function(res) {
        if (res.code === 0) {
          wx.hideToast();
          if (res.data.list.length > 0) {
            let newlist = res.data.list;
            for (let n in newlist) {
              if ({}.hasOwnProperty.call(newlist, n)) {
                newlist[n].type = _type;
              }
            }
            that.setData({
              list: googslist.concat(newlist),
            });
          } else {
            that.setData({
              is_more: false
            });
            if (page > 1) {
              // wx.showToast({
              //   title: '没有更多数据了',
              //   icon: 'none',
              //   duration: 1000,
              // });
            }
          }
          that.setData({
            upNum: res.data.upnum,
            downNum: res.data.downum,
            can_edit_stock: Number(res.data.can_edit_stock) === 1,
            isData2: true
          });
        }
      }
    });
  },
  clearTxt() {
    let catid = this.data.catid;
    let status = this.data.status;
    let limit = this.data.limit;
    this.setData({
      currVal: "",
      keywords: "",
      page: 1,
      list: [],
      isEmpty: true
    });
    this.onGetGoodsList(catid, status, "", 1, limit);
  },
  inputChange(e) {
    let val = e.detail.value;
    if (val.trim()) {
      this.setData({
        isEmpty: false
      });
    } else {
      this.setData({
        isEmpty: true
      });
    }
    this.setData({
      currVal: e.detail.value
    });
  },
  inputConfirm(e) {
    let catid = this.data.catid;
    let keywords = e.detail.value.trim();
    let status = this.data.status;
    let limit = this.data.limit;
    this.setData({
      page: 1,
      keywords,
      list: []
    });
    this.onGetGoodsList(catid, status, keywords, 1, limit);
  },
  searchTxt(keyword) {
    let keywords = keyword;
    let catid = this.data.catid;
    let status = this.data.status;
    let limit = this.data.limit;
    this.setData({
      page: 1,
      keywords,
      list: []
    });
    this.onGetGoodsList(catid, status, keywords, 1, limit);
  },
  searchSure() {
    let keyword = this.data.currVal.trim();
    this.searchTxt(keyword);
  },
  searchCancel() {
    wx.navigateBack({
      delta: 1
    });
  },
  openPop(e) {
    let id = Number(e.currentTarget.dataset.goodsid);
    let goodslist = this.data.list;
    let len = goodslist.length;
    for (let i = 0; i < len; i++) {
      if (Number(goodslist[i].id) === id) {
        goodslist[i].isShow = true;
      } else {
        goodslist[i].isShow = false;
      }
    }
    this.setData({
      list: goodslist,
      goodsID: id
    });
  },
  closePop(e) {
    let id = Number(e.currentTarget.dataset.goodsid);
    let goodslist = this.data.list;
    let len = goodslist.length;
    for (let i = 0; i < len; i++) {
      if (Number(goodslist[i].id) === id) {
        goodslist[i].isShow = false;
        break;
      }
    }
    this.setData({
      list: goodslist
    });
  },
  delList(e) {
    this.setData({
      list: e.detail.list,
      upNum: e.detail.upnum,
      downNum: e.detail.downnum
    });
    wx.showToast({
      title: "操作成功",
      icon: "success"
    });
  },
  changeData(e) {
    let that = this;
    let { use_attr, id } = e.detail;
    let { index } = e.currentTarget.dataset;
    let { list } = that.data;
    that.setData({
      [`list[${index}].isShow`]: false
    });
    if (e.detail.show1) {
      if (Number(use_attr) === 1) {
        let url = `/ws_micro_shop_seller/pages/goods-get-detail/index?id=${id}&type=2`;
        app.util.navigateTo(url);
      } else {
        this.setData({
          showModel1: true
        });
      }
    } else if (e.detail.show2) {
      if (Number(use_attr) === 1) {
        let url = `/ws_micro_shop_seller/pages/goods-get-detail/index?id=${id}&type=2`;
        app.util.navigateTo(url);
      } else {
        this.setData({
          showModel2: true
        });
      }
    } else if (e.detail.scanCode) {
      let goodsId = that.data.goodsID;
      this.setData({
        scanCode: e.detail.scanCode
      });
      app.ws_micro_shoprequest({
        url: api.adminer.getattr,
        method: "POST",
        data: {
          goods_id: goodsId
        },
        success: function(res) {
          console.log("66666666", res);
          if (res.code === 0) {
            that.setData({
              showModel3: true,
              attr_group_list: res.data,
              use_attr: res.use_attr
            });
            that.selectDefaultAttr();
          }
        }
      });
    }
  },
  closeModel() {
    this.setData({
      showModel1: false,
      showModel2: false,
      showModel3: false
    });
  },
  originalPrice(e) {
    let price = e.detail.value.trim();
    this.setData({
      originalPrice: price
    });
  },
  salesPrice(e) {
    let price = e.detail.value.trim();
    this.setData({
      salesPrice: price
    });
  },
  repertory(e) {
    let count = e.detail.value.trim();
    this.setData({
      leaveCount: count
    });
  },
  submitPrice() {
    let that = this;
    let goodslist = this.data.list;
    let len = goodslist.length;
    let goodsId = Number(that.data.goodsID);
    let originalPrice = that.data.originalPrice;
    let salesPrice = that.data.salesPrice;
    if (!that.data.isBrand) {
      if (!originalPrice) {
        wx.showToast({
          title: "商品原价不能为空",
          icon: "none"
        });
        return;
      }
      if (originalPrice < 0.01) {
        wx.showToast({
          title: "商品原价不能低于" + that.data.unit + "0.01",
          icon: "none"
        });
        return;
      }
      if (originalPrice > 99999999) {
        wx.showToast({
          title: "商品原价超过限制",
          icon: "none"
        });
        return;
      }
    }
    if (!salesPrice) {
      wx.showToast({
        title: "商品售价不能为空",
        icon: "none"
      });
      return;
    }
    if (salesPrice < 0.01) {
      wx.showToast({
        title: "商品售价不能低于" + that.data.unit + "0.01",
        icon: "none"
      });
      return;
    }
    if (salesPrice > 99999999) {
      wx.showToast({
        title: "商品售价超过限制",
        icon: "none"
      });
      return;
    }
    app.ws_micro_shoprequest({
      url: api.adminer.operate,
      method: "GET",
      data: {
        goods_id: goodsId,
        type: "update",
        original_price: originalPrice,
        price: salesPrice
      },
      success: function(res) {
        if (res.code === 0) {
          for (let i = 0; i < len; i++) {
            //2019.12.19品牌版修改售价后原价会消失的情况修复--author.yanyong
            if (Number(goodslist[i].id) === goodsId && that.data.isBrand) {
              goodslist[i].price = salesPrice;
              break;
            }else if(Number(goodslist[i].id) === goodsId && !that.data.isBrand){
              goodslist[i].price = salesPrice;
              goodslist[i].original_price = originalPrice;
              break;
            }
          }
          that.setData({
            list: goodslist,
            showModel1: false,
            originalPrice: 0,
            salesPrice: 0
          });
          wx.showToast({
            title: "修改成功",
            icon: "success"
          });
          // wx.redirectTo({
          //   url: '/' + that.route + '?status=' + that.data.status,
          // });
        } else {
          wx.showToast({
            title: res.msg ? res.msg : "操作失败",
            icon: "none"
          });
        }
      }
    });
  },
  openPopCount(e) {
    let id = Number(e.currentTarget.dataset.goodsid);
    this.setData({
      showModel2: true,
      goodsID: id
    });
  },
  submitCount() {
    let that = this;
    let goodslist = this.data.list;
    let len = goodslist.length;
    let goodsId = Number(that.data.goodsID);
    let count = that.data.leaveCount;
    if (!count) {
      wx.showToast({
        title: "商品库存不能为空",
        icon: "none"
      });
      return;
    }
    if (count < 0) {
      wx.showToast({
        title: "商品库存不能少于0",
        icon: "none"
      });
      return;
    }
    app.ws_micro_shoprequest({
      url: api.adminer.operate,
      method: "GET",
      data: {
        goods_id: goodsId,
        type: "update",
        goods_num: count
      },
      success: function(res) {
        if (res.code === 0) {
          for (let i = 0; i < len; i++) {
            if (Number(goodslist[i].id) === goodsId) {
              goodslist[i].remain = count;
              break;
            }
          }
          that.setData({
            list: goodslist,
            showModel2: false,
            leaveCount: ""
          });
          wx.showToast({
            title: "修改成功",
            icon: "success"
          });
          // wx.redirectTo({
          //   url: '/' + that.route + '?status=' + that.data.status,
          // });
        } else {
          wx.showToast({
            title: res.msg ? res.msg : "操作失败",
            icon: "none"
          });
        }
      }
    });
  },
  selectDefaultAttr() {
    let _this = this;
    let attr_group_list = _this.data.attr_group_list;
    if (Number(_this.data.use_attr) !== 0) {
      return;
    }
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        for (let j in attr_group_list[i].attr_list) {
          if (Number(i) === 0 && Number(j) === 0) {
            attr_group_list[i].attr_list[j]["checked"] = true;
          }
        }
      }
    }
    _this.setData({
      attr_group_list
    });
  },
  attrClick(e) {
    let _this = this;
    let attr_group_id = Number(e.currentTarget.dataset.groupId);
    let attr_id = Number(e.currentTarget.dataset.id);
    let attr_group_list = _this.data.attr_group_list;
    for (let i in attr_group_list) {
      if (Number(attr_group_list[i].attr_group_id) !== attr_group_id) {
        continue;
      }
      for (let j in attr_group_list[i].attr_list) {
        if (Number(attr_group_list[i].attr_list[j].attr_id) === attr_id) {
          attr_group_list[i].attr_list[j].checked = true;
        } else {
          attr_group_list[i].attr_list[j].checked = false;
        }
      }
    }
    _this.setData({
      attr_group_list
    });
  },
  bindCancel() {
    this.setData({
      showModel3: false
    });
  },
  bindDone() {
    let _this = this;
    let attr_group_list = _this.data.attr_group_list;
    let checked_attr_list = [];
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        let attr = false;
        for (let j in attr_group_list[i].attr_list) {
          if (attr_group_list[i].attr_list[j].checked) {
            attr = {
              attr_id: attr_group_list[i].attr_list[j].attr_id,
              attr_name: attr_group_list[i].attr_list[j].attr_name
            };
            break;
          }
        }
        if (!attr) {
          wx.showToast({
            title: "请选择" + attr_group_list[i].attr_group_name,
            icon: "none"
          });
          return true;
        } else {
          checked_attr_list.push({
            attr_group_id: attr_group_list[i].attr_group_id,
            attr_group_name: attr_group_list[i].attr_group_name,
            attr_id: attr.attr_id,
            attr_name: attr.attr_name
          });
        }
      }
    }
    app.ws_micro_shoprequest({
      url: api.adminer.inputbarcode,
      method: "POST",
      data: {
        goods_id: _this.data.goodsID,
        attr: JSON.stringify(checked_attr_list),
        code: _this.data.scanCode
      },
      success: function(res) {
        if (res.code === 0) {
          wx.showToast({
            title: "绑定成功",
            icon: "success"
          });
        } else {
          wx.showToast({
            title: "绑定失败",
            icon: "none"
          });
        }
        _this.setData({
          showModel3: false
        });
      }
    });
  }
});
